﻿using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Models.RequestModel;
using RndMaterialDisposalService.Repository;
using RndMaterialDisposalService.Services.Interface;
using Microsoft.Data.SqlClient;
using System.Data;

namespace RndMaterialDisposalService.Services
{
    [NAutowired(Lifecycle.Scoped)]
    public class CapitalRepairReportFormService: ICapitalRepairReportFormService
    {
        private readonly AssetsManagementContext dbContext;
        private readonly UserBaseInforDataContext userBaseInforDataContext;
        public CapitalRepairReportFormService(AssetsManagementContext _dbContext, UserBaseInforDataContext _userBaseInforDataContext) 
        {
            dbContext = _dbContext;
            userBaseInforDataContext = _userBaseInforDataContext;
        }

        /// <summary>
        /// 返回资产转移电子流报表主数据(带分页)
        /// </summary>
        /// <param name="repair"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List<CapitalRepairReportFormModel> GetCapitalRepairReportFormPageList(CapitalRepairReportConditionModel repair) 
        {
            List<CapitalRepairReportFormModel> list = new List<CapitalRepairReportFormModel>();
            List<SqlParameter> sqlParameters = new List<SqlParameter>();
            string condition = "1=1 ";
            if (!string.IsNullOrWhiteSpace(repair.ApplicationNumber))
            {
                condition += $"AND V.ApplicationNumber LIKE '%{repair.ApplicationNumber}%' ";
            }
            if (!string.IsNullOrWhiteSpace(repair.CreatedDate)) 
            {
                string[] timeArr = repair.CreatedDate.Split(',');
                if (timeArr.Length > 0)
                {
                    condition += $"AND V.CreatedDate >= '{timeArr[0]} 00:00:00' AND V.CreatedDate <= '{timeArr[1]} 23:59:59' ";
                }
            }
            if (!string.IsNullOrWhiteSpace(repair.SongCarRenName))
            {
                condition += $"AND V.SongCarRenUserId = '{repair.SongCarRenName}' ";
            }
            if (!string.IsNullOrWhiteSpace(repair.MaintenanceEngineerName))
            {
                condition += $"AND V.MaintenanceEngineerUserId = '{repair.MaintenanceEngineerName}' ";
            }
            if (!string.IsNullOrWhiteSpace(repair.AssetNo)) 
            {
                condition += $"AND V.AssetNo LIKE '%'+@AssetNo+'%' ";
                SqlParameter sqlPara = new SqlParameter("@AssetNo", SqlDbType.NVarChar);
                sqlPara.Value = repair.AssetNo;
                sqlParameters.Add(sqlPara);
            }
            if (!string.IsNullOrWhiteSpace(repair.CurrentStatus))
            {
                condition += $"AND V.CurrentStatus = '{repair.CurrentStatus}' ";
            }
            if (!string.IsNullOrWhiteSpace(repair.CompanySegment))
            {
                condition += $"AND V.CompanySegment LIKE '{repair.CompanySegment}' ";
            }
            if (!string.IsNullOrWhiteSpace(repair.ApplicantName))
            {
                //condition += $"AND V.ApplicantEmployeeNumber = '{repair.ApplicantName}' ";
                condition += $"AND V.ApplicantName LIKE '%{repair.ApplicantName}%' ";
            }
            if (!string.IsNullOrWhiteSpace(repair.ReceivedInKindTime)) 
            {
                string[] timeArr = repair.ReceivedInKindTime.Split(',');
                if (timeArr.Length > 0)
                {
                    condition += $"AND V.ReceivedInKindTime >= '{timeArr[0]} 00:00:00' AND V.ReceivedInKindTime <= '{timeArr[1]} 23:59:59' ";
                }
            }
            if (!string.IsNullOrWhiteSpace(repair.MaintenanceStartTime)) 
            {
                string[] timeArr = repair.MaintenanceStartTime.Split(',');
                if (timeArr.Length > 0)
                {
                    condition += $"AND V.MaintenanceStartTime >= '{timeArr[0]} 00:00:00' AND V.MaintenanceStartTime <= '{timeArr[1]} 23:59:59' ";
                }
            }
            if (!string.IsNullOrWhiteSpace(repair.OutsourcingDeliveryDate))
            {
                string[] timeArr = repair.OutsourcingDeliveryDate.Split(',');
                if (timeArr.Length > 0)
                {
                    condition += $"AND V.OutsourcingDeliveryDate >= '{timeArr[0]} 00:00:00' AND V.OutsourcingDeliveryDate <= '{timeArr[1]} 23:59:59' ";
                }
            }
            if (!string.IsNullOrWhiteSpace(repair.SubcontractingCompletionDate))
            {
                string[] timeArr = repair.SubcontractingCompletionDate.Split(',');
                if (timeArr.Length > 0)
                {
                    condition += $"AND V.SubcontractingCompletionDate >= '{timeArr[0]} 00:00:00' AND V.SubcontractingCompletionDate <= '{timeArr[1]} 23:59:59' ";
                }
            }

            string SqlInsertClip = string.Empty;

            List<WorkflowProcInstIdModel> ApplicationNumberList = new List<WorkflowProcInstIdModel>();

            //插入当前用户查询业务
            if (!string.IsNullOrWhiteSpace(repair.CurrentUser))
            {
                //获取当前用户资产维修电子流审批流程记录,去重后联查得到ProcInstId
                //string _sql = $"SELECT DISTINCT(ApplicationNumber) AS ProcInstId FROM VW_Common.dbo.WorkflowApproveData WHERE WorkflowName = '资产维修电子流' AND ApproverName = '{repair.CurrentUser}'";
                string _sql = $"SELECT a.ProcInstId,c.ApplicationNumber,c.ApproveDate FROM AssetsManagement.dbo.CapitalRepairBusinessData a LEFT JOIN (SELECT DISTINCT(ApplicationNumber),(SELECT MIN(ApproveDate) FROM VW_Common.dbo.WorkflowApproveData WHERE ApplicationNumber = b.ApplicationNumber AND WorkflowName = '资产维修电子流')  AS ApproveDate FROM VW_Common.dbo.WorkflowApproveData b WHERE WorkflowName = '资产维修电子流' AND ApproverName = '{repair.CurrentUser}') c ON c.ApplicationNumber = a.ProcessFolio WHERE ProcInstId !='' AND ApproveDate IS NOT NULL";
                ApplicationNumberList = SqlQuery<WorkflowProcInstIdModel>(_sql,new List<SqlParameter>());

                //审批历史ProcInstId
                var ApprovalHistoryProcInstIdList = ApplicationNumberList.Select(a => a.ProcInstId).ToList();

                //当前用户工号
                string employeeNumber = repair.CurrentUser.Substring(0, repair.CurrentUser.IndexOf(" "));
                //利用UserID获取当前用户工号LaunchList
                //var EmployeeInfo = userBaseInforDataContext.UserBaseInfor.FirstOrDefault(x => x.UserId == UserId);
                if (!string.IsNullOrWhiteSpace(employeeNumber))
                {
                    //获取发起流程实例
                    _sql = $"SELECT ProcInstId FROM VW_Common.dbo.WorkflowApplicationData WHERE ProcInstId !='' AND WorkflowName='资产维修电子流' AND ApplicantEmployeeNumber = '{employeeNumber}'";
                    List<WorkflowProcInstIdModel> LaunchList = SqlQuery<WorkflowProcInstIdModel>(_sql,new List<SqlParameter>());
                    if (LaunchList.Any())
                    {
                        var LaunchProcInstIdList = LaunchList.Select(a => a.ProcInstId).ToList();
                        ApprovalHistoryProcInstIdList.AddRange(LaunchProcInstIdList);
                        ApprovalHistoryProcInstIdList = ApprovalHistoryProcInstIdList.Distinct().ToList();
                    }
                }

                string ApplicationNumber_STR = "''";
                if (ApprovalHistoryProcInstIdList.Any())
                {
                    List<string> _ProcInstIdList = ApprovalHistoryProcInstIdList.Select(a => a = $"'{a.Trim()}'").ToList();
                    ApplicationNumber_STR = string.Join(',', _ProcInstIdList);
                }

                SqlInsertClip = $"(SELECT * FROM AssetsManagement.dbo.CapitalRepairBusinessData WHERE ProcInstId IN({ApplicationNumber_STR}))";
            }
            else 
            {
                SqlInsertClip = "(SELECT * FROM AssetsManagement.dbo.CapitalRepairBusinessData WHERE ProcInstId !='')";
            }

            int startIndex = ((repair.pageIndex - 1) * repair.pageSize) + 1;
            int endIndex = repair.pageSize * repair.pageIndex;

            string sql = @$"SELECT V.[Key],V.ApplicationNumber,V.ProcInstId,V.ApplicantEmployeeNumber,V.CreatedDate,V.SongCarRenUserId,V.SongCarRenName,V.AssetNo,V.AssetName,V.CompanySegment,V.DepartmentName,V.DepartmentNumber,V.DamageTime,V.FactoryNo,V.CurrentStatus,V.ApplicantName,V.MaintenanceEngineerUserId,V.MaintenanceEngineerName
                                   ,V.MeasurementAttribute,V.SupplierName,V.AssetActivationTime,V.MaintenanceContactPerson,V.OriginalValue,V.NetWorth,V.ServiceLife,V.HistoricalMaintenanceCount,V.ReceivedInKindTime,V.MaintenanceStartTime,V.IsInformationConsistency,V.CommitmentCycle,V.InstrumentBrand,V.InstrumentModel,V.WithinTheWarrantyPeriod,V.SubcontractingRepair,V.MaintainerName
                                   ,V.OutsourcingDeliveryDate,V.MaintenanceCosts,V.Price,V.PurchaseDepartmentExpenses,V.DepartmentApprovalExpense,V.DepartmentSignatureDate,V.ReceiptPersonnel,V.SubcontractingCompletionDate,V.FinalPurchasePrice,V.VerificationSupplierName FROM (SELECT ROW_NUMBER()  OVER(ORDER BY V.CreatedDate DESC) AS RowID,V.* FROM (
                            SELECT repair.SysId AS [Key],workflow.ApplicationNumber,workflow.ProcInstId,workflow.ApplicantEmployeeNumber,workflow.CreatedDate,repair.SongCarRenUserId,repair.SongCarRenName,repair.AssetNo,repair.AssetName,repair.CompanySegment,repair.DepartmentName,repair.DepartmentNumber,repair.DamageTime,repair.FactoryNo,workflow.CurrentStatus,workflow.CurrentHandler AS ApplicantName,repair.MaintenanceEngineerUserId,repair.MaintenanceEngineerName
                                   ,repair.MeasurementAttribute,repair.SupplierName,repair.AssetActivationTime,repair.MaintenanceContactPerson,repair.OriginalValue,repair.NetWorth,repair.ServiceLife,repair.HistoricalMaintenanceCount,repair.ReceivedInKindTime,repair.MaintenanceStartTime,repair.IsInformationConsistency,repair.CommitmentCycle,repair.InstrumentBrand,repair.InstrumentModel,repair.WithinTheWarrantyPeriod,repair.SubcontractingRepair,repair.MaintainerName
                                   ,repair.OutsourcingDeliveryDate,repair.MaintenanceCosts,repair.Price,repair.PurchaseDepartmentExpenses,repair.DepartmentApprovalExpense,repair.DepartmentSignatureDate,repair.ReceiptPersonnel,repair.SubcontractingCompletionDate,repair.FinalPurchasePrice,repair.VerificationSupplierName
                            FROM {SqlInsertClip} repair
                            LEFT JOIN VW_Common.dbo.WorkflowApplicationData workflow ON repair.ProcInstId = workflow.ProcInstId) V WHERE {condition}) V 
                            WHERE V.RowID BETWEEN {startIndex} AND {endIndex}";

            list = SqlQuery<CapitalRepairReportFormModel>(sql, sqlParameters);

            list.ForEach((x) => {
                x.ApplicationNumber = x.ApplicationNumber.Trim();
                //维修电子流与实物送修信息是否一致
                x.IsInformationConsistency = x.IsInformationConsistency == "0" ? "否" : "是";
                //保修期内
                x.WithinTheWarrantyPeriod = x.WithinTheWarrantyPeriod == "0" ? "否" : "是";
                //委外维修
                x.SubcontractingRepair = x.SubcontractingRepair == "0" ? "否" : "是";
                //维修费用
                if (x.MaintenanceCosts == "1") 
                {
                    x.MaintenanceCosts = "无";
                }
                else if (x.MaintenanceCosts == "2") 
                {
                    x.MaintenanceCosts = "标准协议价";
                }
                else if (x.MaintenanceCosts == "3") 
                {
                    x.MaintenanceCosts = "单次议价费用";
                }
            });

            //赋值流程最早时间
            if (!string.IsNullOrWhiteSpace(repair.CurrentUser))
            {
                list.ForEach((x) => {
                    var item = ApplicationNumberList.FirstOrDefault(a => a.ProcInstId == x.ProcInstId);
                    if (item != null)
                    {
                        x.CreatedDate = item.ApproveDate;
                    }
                });
            }

            ////去掉当前审批人前缀
            //list.ForEach((x) => {
            //    if (!string.IsNullOrWhiteSpace(x.ApplicantName))
            //    {
            //        x.ApplicantName = x.ApplicantName.Substring(x.ApplicantName.IndexOf(" ") + 1).Trim();
            //    }
            //});

            return list;
        }

        /// <summary>
        /// 返回资产转移电子流报表主数据
        /// </summary>
        /// <param name="repair"></param>
        /// <returns></returns>
        public List<CapitalRepairReportFormModel> GetCapitalRepairReportFormData(CapitalRepairReportConditionModel repair) 
        {
            List<CapitalRepairReportFormModel> list = new List<CapitalRepairReportFormModel>();
            List<SqlParameter> sqlParameters = new List<SqlParameter>();
            string condition = "1=1 ";
            if (!string.IsNullOrWhiteSpace(repair.ApplicationNumber))
            {
                condition += $"AND workflow.ApplicationNumber LIKE '%{repair.ApplicationNumber}%' ";
            }
            if (!string.IsNullOrWhiteSpace(repair.CreatedDate))
            {
                string[] timeArr = repair.CreatedDate.Split(',');
                if (timeArr.Length > 0)
                {
                    condition += $"AND workflow.CreatedDate >= '{timeArr[0]} 00:00:00' AND workflow.CreatedDate <= '{timeArr[1]} 23:59:59' ";
                }
            }
            if (!string.IsNullOrWhiteSpace(repair.SongCarRenName))
            {
                condition += $"AND repair.SongCarRenUserId = '{repair.SongCarRenName}' ";
            }
            if (!string.IsNullOrWhiteSpace(repair.MaintenanceEngineerName))
            {
                condition += $"AND repair.MaintenanceEngineerUserId = '{repair.MaintenanceEngineerName}' ";
            }
            if (!string.IsNullOrWhiteSpace(repair.AssetNo))
            {
                condition += $"AND repair.AssetNo LIKE '%'+@AssetNo+'%' ";
                SqlParameter sqlPara = new SqlParameter("@AssetNo", SqlDbType.NVarChar);
                sqlPara.Value = repair.AssetNo;
                sqlParameters.Add(sqlPara);
            }
            if (!string.IsNullOrWhiteSpace(repair.CurrentStatus))
            {
                condition += $"AND workflow.CurrentStatus = '{repair.CurrentStatus}' ";
            }
            if (!string.IsNullOrWhiteSpace(repair.CompanySegment))
            {
                condition += $"AND repair.CompanySegment = '{repair.CompanySegment}' ";
            }
            if (!string.IsNullOrWhiteSpace(repair.ApplicantName))
            {
                //condition += $"AND workflow.ApplicantEmployeeNumber = '{repair.ApplicantName}' ";
                condition += $"AND workflow.ApplicantName LIKE '%{repair.ApplicantName}%' ";
            }
            if (!string.IsNullOrWhiteSpace(repair.ReceivedInKindTime))
            {
                string[] timeArr = repair.ReceivedInKindTime.Split(',');
                if (timeArr.Length > 0)
                {
                    condition += $"AND repair.ReceivedInKindTime >= '{timeArr[0]} 00:00:00' AND repair.ReceivedInKindTime <= '{timeArr[1]} 23:59:59' ";
                }
            }
            if (!string.IsNullOrWhiteSpace(repair.MaintenanceStartTime))
            {
                string[] timeArr = repair.MaintenanceStartTime.Split(',');
                if (timeArr.Length > 0)
                {
                    condition += $"AND repair.MaintenanceStartTime >= '{timeArr[0]} 00:00:00' AND repair.MaintenanceStartTime <= '{timeArr[1]} 23:59:59' ";
                }
            }
            if (!string.IsNullOrWhiteSpace(repair.OutsourcingDeliveryDate))
            {
                string[] timeArr = repair.OutsourcingDeliveryDate.Split(',');
                if (timeArr.Length > 0)
                {
                    condition += $"AND repair.OutsourcingDeliveryDate >= '{timeArr[0]} 00:00:00' AND repair.OutsourcingDeliveryDate <= '{timeArr[1]} 23:59:59' ";
                }
            }
            if (!string.IsNullOrWhiteSpace(repair.SubcontractingCompletionDate))
            {
                string[] timeArr = repair.SubcontractingCompletionDate.Split(',');
                if (timeArr.Length > 0)
                {
                    condition += $"AND repair.SubcontractingCompletionDate >= '{timeArr[0]} 00:00:00' AND repair.SubcontractingCompletionDate <= '{timeArr[1]} 23:59:59' ";
                }
            }

            string SqlInsertClip = string.Empty;

            List<WorkflowProcInstIdModel> ApplicationNumberList = new List<WorkflowProcInstIdModel>();

            //插入当前用户查询业务
            if (!string.IsNullOrWhiteSpace(repair.CurrentUser))
            {
                //获取当前用户资产维修电子流审批流程记录,去重后联查得到ProcInstId
                //string _sql = $"SELECT DISTINCT(ApplicationNumber) AS ProcInstId FROM VW_Common.dbo.WorkflowApproveData WHERE WorkflowName = '资产维修电子流' AND ApproverName = '{repair.CurrentUser}'";
                string _sql = $"SELECT a.ProcInstId,c.ApplicationNumber,c.ApproveDate FROM AssetsManagement.dbo.CapitalRepairBusinessData a LEFT JOIN (SELECT DISTINCT(ApplicationNumber),(SELECT MIN(ApproveDate) FROM VW_Common.dbo.WorkflowApproveData WHERE ApplicationNumber = b.ApplicationNumber)  AS ApproveDate FROM VW_Common.dbo.WorkflowApproveData b WHERE WorkflowName = '资产维修电子流' AND ApproverName = '{repair.CurrentUser}') c ON c.ApplicationNumber = a.ProcessFolio WHERE ProcInstId !='' AND ApproveDate IS NOT NULL";
                ApplicationNumberList = SqlQuery<WorkflowProcInstIdModel>(_sql,new List<SqlParameter>());

                //审批历史ProcInstId
                var ApprovalHistoryProcInstIdList = ApplicationNumberList.Select(a => a.ProcInstId).ToList();

                //当前用户工号
                string employeeNumber = repair.CurrentUser.Substring(0, repair.CurrentUser.IndexOf(" "));
                //利用UserID获取当前用户工号LaunchList
                //var EmployeeInfo = userBaseInforDataContext.UserBaseInfor.FirstOrDefault(x => x.UserId == UserId);
                if (!string.IsNullOrWhiteSpace(employeeNumber))
                {
                    //获取发起流程实例
                    _sql = $"SELECT ApplicationNumber AS ProcInstId FROM VW_Common.dbo.WorkflowApplicationData WHERE ProcInstId !='' AND WorkflowName='资产维修电子流' AND ApplicantEmployeeNumber = '{employeeNumber}'";
                    List<WorkflowProcInstIdModel> LaunchList = SqlQuery<WorkflowProcInstIdModel>(_sql,new List<SqlParameter>());
                    if (LaunchList.Any())
                    {
                        var LaunchProcInstIdList = LaunchList.Select(a => a.ProcInstId).ToList();
                        ApprovalHistoryProcInstIdList.AddRange(LaunchProcInstIdList);
                        ApprovalHistoryProcInstIdList = ApprovalHistoryProcInstIdList.Distinct().ToList();
                    }
                }

                string ProcInstId_STR = "''";
                if (ApprovalHistoryProcInstIdList.Any())
                {
                    List<string> _ProcInstIdList = ApprovalHistoryProcInstIdList.Select(a => a = $"'{a.Trim()}'").ToList();
                    ProcInstId_STR = string.Join(',', _ProcInstIdList);
                }

                SqlInsertClip = $"(SELECT * FROM AssetsManagement.dbo.CapitalRepairBusinessData WHERE ProcessFolio IN({ProcInstId_STR}))";
            }
            else 
            {
                SqlInsertClip = "(SELECT * FROM AssetsManagement.dbo.CapitalRepairBusinessData WHERE ProcInstId !='')";
            }

            string sql = @$"SELECT repair.SysId AS [Key],workflow.ApplicationNumber,workflow.ProcInstId,workflow.ApplicantEmployeeNumber,workflow.CreatedDate,repair.SongCarRenUserId,repair.SongCarRenName,repair.AssetNo,repair.AssetName,repair.CompanySegment,repair.DepartmentName,repair.DepartmentNumber,repair.DamageTime,repair.FactoryNo,workflow.CurrentStatus,workflow.CurrentHandler AS ApplicantName,repair.MaintenanceEngineerUserId,repair.MaintenanceEngineerName 
                                   ,repair.MeasurementAttribute,repair.SupplierName,repair.AssetActivationTime,repair.MaintenanceContactPerson,repair.OriginalValue,repair.NetWorth,repair.ServiceLife,repair.HistoricalMaintenanceCount,repair.ReceivedInKindTime,repair.MaintenanceStartTime,repair.IsInformationConsistency,repair.CommitmentCycle,repair.InstrumentBrand,repair.InstrumentModel,repair.WithinTheWarrantyPeriod,repair.SubcontractingRepair,repair.MaintainerName
                                   ,repair.OutsourcingDeliveryDate,repair.MaintenanceCosts,repair.Price,repair.PurchaseDepartmentExpenses,repair.DepartmentApprovalExpense,repair.ReceiptPersonnel,repair.SubcontractingCompletionDate,repair.FinalPurchasePrice,repair.VerificationSupplierName
                            FROM {SqlInsertClip} repair
                            LEFT JOIN VW_Common.dbo.WorkflowApplicationData workflow ON repair.ProcInstId = workflow.ProcInstId WHERE {condition}";

            list = SqlQuery<CapitalRepairReportFormModel>(sql, sqlParameters);

            list.ForEach((x) => {
                x.ApplicationNumber = x.ApplicationNumber.Trim();
                //维修电子流与实物送修信息是否一致
                x.IsInformationConsistency = x.IsInformationConsistency == "0" ? "否" : "是";
                //保修期内
                x.WithinTheWarrantyPeriod = x.WithinTheWarrantyPeriod == "0" ? "否" : "是";
                //委外维修
                x.SubcontractingRepair = x.SubcontractingRepair == "0" ? "否" : "是";
                //维修费用
                if (x.MaintenanceCosts == "1")
                {
                    x.MaintenanceCosts = "无";
                }
                else if (x.MaintenanceCosts == "2")
                {
                    x.MaintenanceCosts = "标准协议价";
                }
                else if (x.MaintenanceCosts == "3")
                {
                    x.MaintenanceCosts = "单次议价费用";
                }
            });

            //赋值流程最早时间
            if (!string.IsNullOrWhiteSpace(repair.CurrentUser))
            {
                list.ForEach((x) => {
                    var item = ApplicationNumberList.FirstOrDefault(a => a.ProcInstId == x.ProcInstId);
                    if (item != null)
                    {
                        x.CreatedDate = item.ApproveDate;
                    }
                });
            }

            ////去掉当前审批人前缀
            //list.ForEach((x) => {
            //    if (!string.IsNullOrWhiteSpace(x.ApplicantName))
            //    {
            //        x.ApplicantName = x.ApplicantName.Substring(x.ApplicantName.IndexOf(" ") + 1).Trim();
            //    }
            //});
            return list;
        }

        /// <summary>
        /// 新增资产维修电子流业务数据
        /// </summary>
        /// <param name="repair"></param>
        /// <returns></returns>
        public async Task<int> AddCapitalRepairBusinessData(CapitalRepairBusinessDataModel repair) 
        {
            dbContext.CapitalRepairBusinessData.Add(repair);
            return await dbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 修改资产维修电子流业务数据
        /// </summary>
        /// <param name="repair"></param>
        /// <returns></returns>
        public async Task<int> EditCapitalRepairBusinessData(CapitalRepairBusinessDataModel repair) 
        {
            var item = await dbContext.CapitalRepairBusinessData.FirstOrDefaultAsync(a => a.ProcInstId == repair.ProcInstId);
            if (item != null)
            {
                item.SongCarRenName = repair.SongCarRenName;
                item.ContactNumber = repair.ContactNumber;
                item.CompanySegment = repair.CompanySegment;
                item.AssetNo = repair.AssetNo;
                item.DepartmentName = repair.DepartmentName;
                item.AssetName = repair.AssetName;
                item.MeasurementAttribute = repair.MeasurementAttribute;
                item.DepartmentNumber = repair.DepartmentNumber;
                item.FactoryNo = repair.FactoryNo;
                item.SupplierName = repair.SupplierName;
                item.DamageTime = repair.DamageTime;
                item.AssetActivationTime = repair.AssetActivationTime;
                item.SelfInquiry = repair.SelfInquiry;
                item.FaultDescription = repair.FaultDescription;
                item.UsageDescription = repair.UsageDescription;
                item.CauseOfFailure = repair.CauseOfFailure;
                item.NotesID = repair.NotesID;
                item.MaintenanceContactPerson = repair.MaintenanceContactPerson;
                item.IsRiskAssessment = repair.IsRiskAssessment;
                item.OriginalValue = repair.OriginalValue;
                item.NetWorth = repair.NetWorth;
                item.ServiceLife = repair.ServiceLife;
                item.HistoricalMaintenanceCount = repair.HistoricalMaintenanceCount;
                item.MaintenanceEngineerName = repair.MaintenanceEngineerName;
                item.ReceivedInKindTime = repair.ReceivedInKindTime;
                item.MaintenanceStartTime = repair.MaintenanceStartTime;
                item.IsInformationConsistency = repair.IsInformationConsistency;
                item.CommitmentCycle = repair.CommitmentCycle;
                item.InstrumentBrand = repair.InstrumentBrand;
                item.InstrumentModel = repair.InstrumentModel;
                item.WithinTheWarrantyPeriod = repair.WithinTheWarrantyPeriod;
                item.SubcontractingRepair = repair.SubcontractingRepair;
                item.MaintainerName = repair.MaintainerName;
                item.RepairContactNumber = repair.RepairContactNumber;
                item.OutsourcingDeliveryDate = repair.OutsourcingDeliveryDate;
                item.SupplierEmail = repair.SupplierEmail;
                item.SubcontractingCompletionDate = repair.SubcontractingCompletionDate;
                item.FeedbackSummary = repair.FeedbackSummary;
                item.MaintenanceCosts = repair.MaintenanceCosts;
                item.Price = repair.Price;
                item.FaultPhenomenonConfirmation = repair.FaultPhenomenonConfirmation;
                item.MaintenanceImplementation = repair.MaintenanceImplementation;
                item.OperationPrecautions = repair.OperationPrecautions;
                item.PurchaseDepartmentExpenses = repair.PurchaseDepartmentExpenses;
                item.DepartmentApprovalExpense = repair.DepartmentApprovalExpense;
                item.ReceiptPersonnel = repair.ReceiptPersonnel;
                item.SongCarRenUserId = repair.SongCarRenUserId;
                item.NotesUserId = repair.NotesUserId;
                item.MaintenanceContactPersonUserId = repair.MaintenanceContactPersonUserId;
                item.MaintenanceEngineerUserId = repair.MaintenanceEngineerUserId;
                item.PurchaseDepartmentExpensesUserId = repair.PurchaseDepartmentExpensesUserId;
                item.DepartmentApprovalExpenseUserId = repair.DepartmentApprovalExpenseUserId;
                item.ReceiptPersonnelUserId = repair.ReceiptPersonnelUserId;
                item.DepartmentSignatureDate = repair.DepartmentSignatureDate;
                item.FinalPurchasePrice = repair.FinalPurchasePrice;
                item.VerificationSupplierName = repair.VerificationSupplierName;
            }

            dbContext.CapitalRepairBusinessData.Attach(item);
            return await dbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 根据流程实例ID查询资产维修电子流信息
        /// </summary>
        /// <param name="ProcInstId"></param>
        /// <returns></returns>
        public async Task<CapitalRepairBusinessDataModel> GetCapitalRepairBusinessDataFind(string ProcInstId) 
        {
            CapitalRepairBusinessDataModel capitalRepairBusinessData = null;
            if (!string.IsNullOrWhiteSpace(ProcInstId)) 
            {
                capitalRepairBusinessData = await dbContext.CapitalRepairBusinessData.FirstOrDefaultAsync(a => a.ProcInstId == ProcInstId);
            }
            return capitalRepairBusinessData;
        }

        /// <summary>
        /// 执行sql
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="sqlParameters"></param>
        /// <returns></returns>
        public List<T> SqlQuery<T>(string sql,List<SqlParameter> sqlParameters) where T : class, new()
        {
            List<T> list = new List<T>();
            var conn = dbContext.Database.GetDbConnection();
            var comm = conn.CreateCommand();
            try
            {
                conn.Open();
                comm.CommandText = sql;
                if (sqlParameters.Count > 0)
                {
                    sqlParameters.ForEach((x) => {
                        comm.Parameters.Add(x);
                    });
                }

                var dr = comm.ExecuteReader();
                while (dr.Read())
                {
                    T t = new T();
                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        var columnName = dr.GetName(i);
                        var colDataType = dr.GetFieldType(i);
                        var item = dr.GetFieldValue<object>(i);
                        if (item == DBNull.Value)
                        {
                            item = null;
                        }
                        //var fieid = t.GetType().GetField(columnName);
                        //fieid?.SetValue(t, item);
                        var property = t.GetType().GetProperty(columnName);
                        property?.SetValue(t, item);
                    }
                    list.Add(t);
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (conn != null && conn.State != System.Data.ConnectionState.Closed)
                {
                    conn.Close();
                }
            }

            return list;
        }
    }
}
